package com.xm.settlement.service.impl;


import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.util.concurrent.AtomicDouble;


import com.xm.settlement.commons.base.ApiResult;
import com.xm.settlement.commons.base.ApiSQLException;
import com.xm.settlement.commons.utils.RedisBeanUtils;
import com.xm.settlement.commons.utils.StringUtils;
import com.xm.settlement.commons.utils.VipUtils;
import com.xm.settlement.mapper.AppScoreLogMapper;
import com.xm.settlement.mapper.AppShopLogMapper;
import com.xm.settlement.model.*;
import com.xm.settlement.model.vo.AppUserVo;
import com.xm.settlement.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Administrator on 2017/2/9.
 * //-- 平台计算规则修改
 *
 */
@Service
public class AppShopLogServiceImpl extends SuperServiceImpl<AppShopLogMapper,AppShopLog> implements AppShopLogService {
    private Logger logger = LoggerFactory.getLogger(AppShopLogServiceImpl.class);

    @Autowired private RedisCacheUtil<AppUserVo> redisCacheUtil;
    @Autowired private RedisCacheUtil<AppBase> baseRedisCacheUtil;
    @Autowired @Qualifier("redisTemplate") public RedisTemplate redisTemplate;
    @Autowired private AppUserService appUserService;
    @Autowired private AppRechargeService appRechargeService;
    @Autowired private AppScoreLogService appScoreLogService;
    @Autowired private AppScoreLogMapper appScoreLogMapper;
    @Autowired private AppUserManageService appUserManageService;
    @Autowired private IAppBaseService appBaseService;

    /**
     *  todo 有空回来优化，各种参数变量,但愿有那么一天
     * */

    /** The lock protecting all mutators */
    final transient ReentrantLock lock = new ReentrantLock();

    CopyOnWriteArrayList<AppUserVo> childrenList = new CopyOnWriteArrayList<AppUserVo>();
    CopyOnWriteArrayList<AppUserVo> agentAppUserList = new CopyOnWriteArrayList<AppUserVo>();

    AtomicInteger atomicInteger ;

    ApiResult apiResult = new ApiResult();
    AppUserManage appUserManage = new AppUserManage();
    BigDecimal bd  ;
    //充值人
    private  AppUserVo rechargeUserVo = new AppUserVo();
   //上级直属人
    private  AppUserVo parentUserVo =  new AppUserVo();
    // 下级团队人
    List<AppUserVo> firstChildrenList = new CopyOnWriteArrayList<AppUserVo>();
    //合作奖收益团队
    List<AppUserVo> cooperationUserList = new CopyOnWriteArrayList<AppUserVo>();
    // 互助奖list
    CopyOnWriteArrayList seeOptionsList = new CopyOnWriteArrayList();
    //团队单修改
    CopyOnWriteArrayList<AppUserManage>  teamDirectList = new CopyOnWriteArrayList<AppUserManage>();
    //-- 充值金额
    private AtomicDouble rechargeAward = new AtomicDouble();

    private int log_score_table = 1 ; //积分变动表

    /**
     * @param orderCode
     * @param vipCode
     * @desc 充值入口
     * @return
     * */
    @Override
    public ApiResult insertDynamicIncome(String orderCode, String vipCode,double awards) {
         return null;
    }


    @Override
    public ApiResult<AppUser> changeDynamicIncome(String vipCode, double awards) throws ApiSQLException{
        ReentrantLock lock = this.lock;
        lock.lock();
        apiResult = new ApiResult();
        try{
            rechargeUserVo = new AppUserVo();
            rechargeUserVo.setVip_code(vipCode);
            rechargeAward = new AtomicDouble(awards);
            rechargeUserVo.setAwards(awards);

         //   redisTemplate.multi();
            if(insertSataicIncomeForSelf()){
                return  apiResult;
            }
            if( inserttDynamicIncomeForSelf() ){
                return  apiResult;
            }
            /**-----------------------------
              动态收益部分
              动态动态收益分为4部分计算 分享奖 合作奖 代理奖 互助奖
             -------------------------------*/
            rechargeUserVo.setAwards(awards);
            updateDirectNum(rechargeUserVo);

            apiResult.setCode("800");
            apiResult.setMsg("充值成功");
            return apiResult;
        }catch (SQLException e){
            e.printStackTrace();
            logger.info("数据库执行异常...."+e.getMessage());
            throw new ApiSQLException(5000,"程序异常");
        }finally {
            lock.unlock();
        }
    }



    /**
     * 修改单数
     * */
    public void updateDirectNum(AppUserVo appUserVo) throws  SQLException{
        logger.info(" ----------------------------- ");
        logger.info("  修改订单数目 " + appUserVo.getVip_code() );
        logger.info(" ----------------------------- ");
        double arawds = appUserVo.getAwards();
        appUserVo = getAppUser(appUserVo.getVip_code());
        if(appUserVo.getPush_code() == null || StringUtils.isEmpty(appUserVo.getPush_code())){
               return   ;
        }
        AppUserVo firstAppUserVo =   getAppUser(appUserVo.getPush_code());
        if(firstAppUserVo == null ){
            return ;
        }
        /**--------------------------
         *  直推单
         ---------------------------*/
        AppUserManage firstAppUser  = new AppUserManage();
        firstAppUser.setVip_code(firstAppUserVo.getVip_code());
        firstAppUser.setDirect_num(1);
        firstAppUser.setIndirect_num(arawds);

        teamDirectList = new CopyOnWriteArrayList<AppUserManage>();
        appUserManageService.updateAppUserManageByVipCode(firstAppUser);

        getAppUserManage(firstAppUserVo);

        if(teamDirectList != null && !teamDirectList.isEmpty()){
            updateDirectNums(teamDirectList,arawds);
        }

        /**--------------------------
         *  修改代理级别
         ---------------------------*/
        teamDirectList.add(firstAppUser);
        updateLevel(teamDirectList);
    }

    /**
     * 修改单据里的全部人级别
     * */
    public void  updateLevel(List<AppUserManage> appUserManageList){
       // 代理级别 2 3 4 5 6
        for ( int i = 1 ; i < 7 ; i++ ){
            getLevelMap(i,appUserManageList);
        }
         //-- 重新更新redis 数据
        List<AppUserVo> userVoList = appUserService.selectUserVoList();
        for(AppUserVo userVo : userVoList ){
            redisCacheUtil.setCacheObject(RedisBeanUtils.USER_VO_MAP +"_"+ userVo.getVip_code(),userVo);
        }
    }

    /**
     *  修改代理级别根据条件
     * */
    public void getLevelMap(Integer level,List<AppUserManage> appUserManageList ){
        Map map = new HashMap();
        map.put("direct_num", getAppBase("agent_direct_level",level.toString()).getPercentage());
        map.put("indirect_num",getAppBase("agent_indirect_level",level.toString()).getPercentage()*10000);
        map.put("vip_level",level);
        map.put("list",appUserManageList);
        appUserManageService.updateAppUserManageLevelByVipCode(map);
    }


    public void updateDirectNums(List<AppUserManage> appUserManagesList,Double awards)throws SQLException{
        Map map = new HashMap();
        List<String> stringList = new ArrayList<String>();
        for (AppUserManage appUserManage : appUserManagesList){
            stringList.add(appUserManage.getVip_code());
        }
        int eachInt =  stringList.size() % 500 == 0 ? ( stringList.size() / 500 ): ( stringList.size() / 500 + 1 );
        for (int i = 0 ;i < eachInt  ;i++ ){
            if( i  == eachInt - 1 ){
                map.put("stringList",stringList.subList( i*500 , i*500 + stringList.size()%500 ));
            }else{
                map.put("stringList",stringList.subList( i*500 , i*500+500 ));
            }
            map.put("indirect_num",awards);
            appUserManageService.updateAppUserDirectNumInVipCode(map);
            //-- todo 代理级别发生变化 需要记录

        }
    }


    /**
     * 递归往上查找
     * */
    public void getAppUserManage( AppUserVo firstAppUserVo) throws SQLException{
        AppUserManage firstAppManage = new AppUserManage();
        if(firstAppUserVo.getPush_code() == null ){
            return;
        }
        firstAppUserVo =   getAppUser(firstAppUserVo.getPush_code());
        if(firstAppUserVo == null ){
            return;
        }else{
            firstAppManage.setVip_code(firstAppUserVo.getVip_code());
            teamDirectList.add(firstAppManage);
            getAppUserManage(firstAppUserVo);
        }
    }

    /**
     *  动态收益部分start
     * */
    public boolean inserttDynamicIncomeForSelf() throws ApiSQLException {
            //分享奖
        Integer isUseShare =  getAppBase("is_show_share","1").getPercentage();
        if(isUseShare != null && isUseShare == 1 ){
            if(insertMutualAidAward( rechargeUserVo)){
                return  true;
            }
        }
           if(insertShareAward( )){
               return true;
           }
            // 互助奖
        //此功能暂不开放[开放请修改数据库字段]
            Integer isUseSeepoint =  getAppBase("is_show_see_point","1").getPercentage();
            if(isUseSeepoint != null && isUseSeepoint == 1 ){
                if(insertMutualAidAward( rechargeUserVo)){
                    return  true;
                }
            }
           // 合作奖
            Integer isUse =  getAppBase("is_show_cooperation","1").getPercentage();
            if(isUse != null &&  isUse == 1){
                if(insertCooperationAward(rechargeUserVo )){
                    return  true;
                }
            }
                // 代理奖
            Integer isUseAgent =  getAppBase("is_show_agent","1").getPercentage();
            if(isUseAgent != null &&  isUseAgent == 1){
                if(insertAgentAward(rechargeUserVo)){
                    return true;
                }
            }
            return false;
    }

    /**
     *  互助奖（见点奖）：1%/10层() 2%
     *  向上找10个人
     * */
    private boolean insertMutualAidAward(AppUserVo appUserVo) throws ApiSQLException {
            seeOptionsList = new CopyOnWriteArrayList();
            atomicInteger = new AtomicInteger(0);
            bd = new BigDecimal( getAppBase("cooperation_award","1").getPercentage());
            bd.setScale(2);
            float percentage =  bd.floatValue() /100 ;
            double cooperationAward = appUserVo.getAwards() * percentage;
            appUserVo =  getAppUser(appUserVo.getPush_code());
            logger.info("------------------ 互助奖start  ----------------------------");
            if( appUserVo != null ){ // 第一层客户信息
                atomicInteger.addAndGet(1);
                seeOptionsList.add(appUserVo);
                getParentUser(appUserVo.getPush_code());
                double avgAward = cooperationAward/atomicInteger.intValue();
                avgAward  =  charging(avgAward);
                logger.info(" 总人数: "+ atomicInteger );
                logger.info(" 金额: "+ avgAward );
                //-- 修改金额
                updateDealData(avgAward,seeOptionsList,appUserVo.getVip_code());
            }
            logger.info("------------------ 互助奖end  ----------------------------");
        return false;
    }

    /**
     *  递归查询互助奖全部人员 10层
     * */
    public void getParentUser(String vipCode){
        if(atomicInteger.intValue() >= 10){
            return ;
        }
        AppUserVo  appUserVo =  getAppUser(vipCode);
        if( appUserVo != null ){ // first custom info
            atomicInteger.addAndGet(1);
            seeOptionsList.add(appUserVo);
            getParentUser(appUserVo.getPush_code());
        }
    }


    /**
     * 合作奖
     *  上拿1代和下一代收入收益的2%加权分配。
     * */
    private boolean insertCooperationAward(AppUserVo appUserVo) throws ApiSQLException {
        cooperationUserList = new CopyOnWriteArrayList<AppUserVo>();
        //-- 直属推荐人编号  上一代 有且仅有一个
        // 上级直接对接人
        AtomicInteger atomicInteger ;
        parentUserVo = getAppUser(getAppUser(appUserVo.getVip_code()).getPush_code());
        if(parentUserVo == null ){
            atomicInteger = new AtomicInteger(0);
        }else{
            atomicInteger = new AtomicInteger(1);
        }
        //-- 下一代 可能有N个
        //List<AppUserVo> appUserManageL = redisCacheUtil.getCacheList(RedisBeanUtils.USER_VO_LIST +"_"+ appUserVo.getVip_code());
        if( firstChildrenList != null && !firstChildrenList.isEmpty() ){
            atomicInteger.addAndGet(firstChildrenList.size());
            cooperationUserList.addAll(firstChildrenList);
        }
        // total atomicInteger
        if(atomicInteger.intValue() <= 0){//没有上级和下级 // todo 没有上级和下级 金额  主动流失
            return false;
        }else{
            logger.info("------------  合作奖部分日志 start ------------------------------");
            bd = new BigDecimal( getAppBase("cooperation_award","1").getPercentage());
            bd.setScale(2) ;
            double cooperationAward =  appUserVo.getAwards() * (bd.doubleValue()/100)/atomicInteger.intValue();
            double avgCooperationAward = charging(  Double.valueOf( cooperationAward ) ) ;
            logger.info(" 人数 : "+atomicInteger.intValue());
            logger.info(" 总金额 : "+cooperationAward);
            logger.info(" 平均结果 :" + avgCooperationAward);
            //-- 2
            cooperationUserList.add(parentUserVo);
            updateDealData(avgCooperationAward,cooperationUserList,appUserVo.getVip_code());
            logger.info("------------  合作奖部分日志 end ------------------------------");
        }
        return false;
    }

    /**
     *  每次500条处理数据
     *  修改现金数据 奖励
     * */
    public void  updateDealData(double avgCooperationAward,List<AppUserVo> appUserManageL,String vip_code){
        Map map = new HashMap();
        map.put("cash_score",avgCooperationAward);
        List<String> stringList = new ArrayList<String>();
        for (AppUserVo appUserVo : appUserManageL){
            stringList.add(appUserVo.getVip_code());
            stringList.add(appUserVo.getVip_code());
        }
       int eachInt = stringList.size() % 500 == 0 ? (stringList.size() / 500) : (stringList.size() / 500 + 1);
        for (int i = 0 ;i < eachInt  ;i++ ){
            if( i  == eachInt - 1 ){
                map.put("stringList",stringList.subList( i * 500 , i * 500 + stringList.size() % 500 ));
            }else{
                map.put("stringList",stringList.subList( i * 500 , i * 500 + 500 ));
            }
            /* --------------------------------------------------
             *      现金积分增值计算
             * --------------------------------------------------*/
            appUserManageService.updateAppUserManageInVipCode(map);
            map.put("vip_code",vip_code);
            map.put("old_score", VipUtils.score_1);
            map.put("new_score",VipUtils.score_1);
            map.put("type",2);
            bd = new BigDecimal(avgCooperationAward);
            map.put("num_value", bd.doubleValue());
            /* --------------------------------------------------
             *      积分增长记录
             * --------------------------------------------------*/
            appScoreLogService.insertScoreLogSuccess(map);
            /* --------------------------------------------------
             *      积分未增长记录
             * --------------------------------------------------*/
            appScoreLogService.insertScoreLogFail(map);
        }
    }


    /**
     * @原始需求
     *  代理奖
     *  全部 总和为 15% 然后依次往下寻找最近的代理人 并记录进list 集合 直到 找到最后一个顶层节点
     //-- 代理奖 计算规则
     //-- 正常情况下 董事→省代→市代→区代→普代→会员 15% = 3% + 3% + 3% + 3% + 3%
     //-- 但是也存在情况 中间断层的情况 情形 如   董事→市代→普代 15% = 3% + 3% +9%
     // -- 不管情况是怎么一回事 需要做的事情就是  董事→省代→区代→普代 15% = 3% + 3% +9%
     * */
    /***
     * @time 2017-4-1
     * @最新需求
     * 代理分为初代、旗下直推2人，业绩大于9万，可获新增业绩的4%．
     * 普通代理旗下3人，业绩大于30万，可获新增业绩的6%．
     * 区级代理旗下直推4人．业绩大于90万．可获新增业绩的8%．
     * 市级代理，旗下直推5人，业绩大于300万．可获新增业绩的10%．
     * 省级代理．旗下直推6人，业绩大于600万丶可获新增业绩的12%．
     * 董事．旗下直推7人．业绩大于1800万．可获新增业绩的15%．
     *  2% 2%
     * */
    private boolean insertAgentAward(AppUserVo appUserVo) throws ApiSQLException{
        AppUserVo  thisUserVo = getAppUser(appUserVo.getVip_code());
        if(thisUserVo == null){
            logger.info("------------------没有查询到当前充值人的详细情况------------------------");
            return  false;
        }
        logger.info("---------------  代理奖计算start ------------------------------");
        int vipLevel = thisUserVo.getVip_level() == null? 1 : thisUserVo.getVip_level();
        agentAppUserList = new CopyOnWriteArrayList();
        if( vipLevel >= VipUtils.vip_level_6){ //   当前充值人为董事，将没有代理奖分配.
            return  false;
        }else{
            getParentUserVo(thisUserVo);
        }
        //    没有上级 代理奖作废
        if( agentAppUserList == null || agentAppUserList.size() <= 0 ){
            return  false;
        }else{
            // list集合进行将序排序
            Collections.sort(agentAppUserList, new CompareUnit());
            int length  = agentAppUserList.size();
            float last = 0.15f ; //;new BigDecimal(getAppBase(VipUtils.agent_award_count,"1").getPercentage()).setScale(2).floatValue()/100;
            //float agent_award_range = new BigDecimal(getAppBase(VipUtils.agent_award_range,"1").getPercentage()).setScale(2).floatValue()/100;
            float agent_award_range = 0.02f;
            float agent_award_range1 = 0.03f;

            for ( int i = 0 ; i < length - 1 ; i++  ){
                if( i == length-1  && agentAppUserList.get(i).getVip_level() == 6 ){
                    updateDealData( charging(appUserVo.getAwards() * last ) ,agentAppUserList.subList(0,1), appUserVo.getVip_code());
                    return false;
                }else if( i < length-1  && agentAppUserList.get(i).getVip_level() == 6 ){
                    last = last - agent_award_range1 ;//董事层收益计算
                }else{//---其他层级计算
                    last = last - agent_award_range ;
                }
            }

            double lastCashScore = charging(  appUserVo.getAwards() * last  );
            updateDealData( lastCashScore,agentAppUserList.subList(0,1), appUserVo.getVip_code());
            logger.info("直推代理的收益:"+ lastCashScore);

            double avgCashScore = charging( appUserVo.getAwards() * agent_award_range ) ;
            updateDealData( avgCashScore,agentAppUserList.subList(1,agentAppUserList.size()-1 ), appUserVo.getVip_code());
            logger.info("非董事代理其他人的收益:"+ avgCashScore);

            double dagent_award_range1 = charging(appUserVo.getAwards() * agent_award_range1);
            updateDealData( dagent_award_range1,agentAppUserList.subList(agentAppUserList.size()-1,agentAppUserList.size() ), appUserVo.getVip_code());
            logger.info("董事代理其他人的收益:"+ agent_award_range1);

        }
        logger.info("---------------  代理奖计算end ------------------------------");
        return  false;
    }

    /**
     * 代理查询 一层一层向上查找
     * */
    public void getParentUserVo(AppUserVo appUserVo){
        AppUserVo parentAppUserVo = getAppUser(appUserVo.getPush_code());
        if( parentAppUserVo != null &&  parentAppUserVo.getVip_level() != null ){  //有直推人的情况
           if(parentAppUserVo.getVip_level() >= VipUtils.vip_level_6 ){
                agentAppUserList.add(parentAppUserVo);
            }else  if( appUserVo.getVip_level() >=  parentAppUserVo.getVip_level()){  // 是直推人但是同级别，所以没有代理奖励.
               if( parentAppUserVo.getPush_code() == null ){
                   return;
               }
                getParentUserVo(parentAppUserVo);
           }else{
                agentAppUserList.add(parentAppUserVo);
               if(parentAppUserVo.getPush_code() == null){
                 return;
               }
               getParentUserVo(parentAppUserVo);
            }
        }
    }

    /**
     *  静态收益计算开始Start
     *   //-- 记录投注日志
     * */
    public boolean insertSataicIncomeForSelf() throws ApiSQLException {
        AppRecharge appRecharge = new AppRecharge();
        appRecharge.setVip_code(rechargeUserVo.getVip_code());
        appRecharge.setMoneys(rechargeUserVo.getAwards());
        appRecharge.setCreate_time(new Date());
        appRechargeService.insert(appRecharge);
        return   insertStaticIncome( );
    }

    /**
     * 静态收益部分
     */
    private boolean insertStaticIncome() throws ApiSQLException  {
        appUserManage.setVip_code(rechargeUserVo.getVip_code());
        if(  VipUtils.cashLevelArr.get( Double.valueOf(rechargeUserVo.getAwards()).intValue() ) != null  ){
              if( insertStaticIncome(   appUserManage, getAppBase(VipUtils.cash_score,"1").getPercentage() ) ){
                  return  true;
              }
        }else{
            logger.info(rechargeUserVo.getVip_code()+" : ");
            logger.info("-----充值金额不能匹配到系统指定额度---------");
            /////////////////////////////////////////////////////////////
            throw new ApiSQLException(4001,"充值金额不能匹配到系统指定额度");
        }
        //   修改数据的正确性
        appUserManageService.updateAppUserManageByVipCode(appUserManage);
        return false;
    }

    public boolean insertStaticIncome( AppUserManage appUserManage,Integer multiple) throws ApiSQLException  {
        AppScoreLog appScoreLog = new AppScoreLog();
        appScoreLog.setCreate_time(new Date());
        appScoreLog.setVip_code(rechargeUserVo.getVip_code());
        appScoreLog.setNew_score(VipUtils.score_4);
        appScoreLog.setOld_score(VipUtils.score_4);
        double shopScore = (rechargeUserVo.getAwards() * getAppBase(VipUtils.shop_score,"1").getPercentage() )/ 4;
        appScoreLog.setNum_value( shopScore );
        appScoreLog.setType(2);
        boolean b = appScoreLogService.insert(appScoreLog);
        if(!b){
            logger.info(rechargeUserVo.getVip_code()+" : ");
            logger.info("  送购物积分失败 ");
            throw new ApiSQLException(4002,"送购物积分失败");
        }
        appUserManage.setShop_score(rechargeUserVo.getAwards() / 4 );
        //（2）送期权积分，三年转为股权
        appScoreLog.setVip_code(rechargeUserVo.getVip_code());
        appScoreLog.setNew_score(VipUtils.score_3);
        appScoreLog.setOld_score(VipUtils.score_3);
        double optionScore = rechargeUserVo.getAwards() * getAppBase(VipUtils.option_score,"1").getPercentage();
        appScoreLog.setNum_value(optionScore);
        appScoreLog.setType(2);
        b = appScoreLogService.insert(appScoreLog);
        if(!b){
            logger.info(rechargeUserVo.getVip_code()+" : ");
            logger.info("  送期权积分失败 ");
            throw new ApiSQLException(4003,"送期权积分失败");
        }
        appUserManage.setOption_score(rechargeUserVo.getAwards());
        //（3）送6000现金积分，新增业绩的20%比例加权分配。
        appScoreLog.setVip_code(rechargeUserVo.getVip_code());
        appScoreLog.setNew_score(VipUtils.score_1);
        appScoreLog.setOld_score(VipUtils.score_1);
        bd = new BigDecimal( 100 -  getAppBase(VipUtils.cash_score,"2").getPercentage());
        bd.setScale(2);
        double cashScore = multiple * rechargeUserVo.getAwards() *     (float) (bd.doubleValue()/100);
        appScoreLog.setNum_value(cashScore);
        appScoreLog.setType(2);

        b = appScoreLogService.insert(appScoreLog);
        //现金积分
        appUserManage.setCash_score(cashScore);

        AppUserManage appUserManage2 = new AppUserManage();
        appUserManage2.setOption_score(optionScore);
        appUserManage2.setVip_code(rechargeUserVo.getVip_code());
        appUserManage2.setCash_score(cashScore);
        appUserManage2.setShop_score(shopScore);

        // B钱包数据
        String b_wallet_type = "0";
        switch(Double.valueOf(rechargeUserVo.getAwards()).intValue()){
            case  3000 :
                b_wallet_type = "1";
                break ;
            case  9000 :
                b_wallet_type = "2";
                break ;
            case  30000 :
                b_wallet_type = "3";
                break ;
            case  60000 :
                b_wallet_type = "4";
                break ;
        }
        appUserManage2.setPresent_score(  getAppBase(VipUtils.b_wallet,b_wallet_type).getPercentage() * rechargeUserVo.getAwards()  );
        appUserManageService.updateRechargeByObject(appUserManage2);
        if(!b){
            logger.info(rechargeUserVo.getVip_code()+" : ");
            logger.info("  送现金积分失败 ");
            throw new ApiSQLException(4004,"送现金积分失败");
        }

        appUserManage.setCash_score(rechargeUserVo.getAwards() *  (float) (bd.doubleValue()/100)  );
        //---------------------------------------------
        //  加权计算 [ 此处的人为团队下全部人]
        //---------------------------------------------
        bd = new BigDecimal(getAppBase(VipUtils.cash_score,"2").getPercentage());
        bd.setScale(2);
        double weightScore =  rechargeUserVo.getAwards() *      bd.doubleValue()/100 ;
        logger.info("静态收益 合作奖20% : "+ weightScore);
        firstChildrenList = appUserService.getChildrenNodeByParentVipCode(rechargeUserVo.getVip_code());

        // -- 下属第一代人
       // redisCacheUtil.setCacheList(RedisBeanUtils.USER_VO_LIST+"_"+appUserVo.getVip_code(),appUserManageL);

        if(firstChildrenList == null ||  firstChildrenList.isEmpty() ){
             //   如果他的团队下没有任何人  系统积分不送
            logger.info("------ 当前充值人无团队 -------");
            return  false;
        }
        childrenList = new CopyOnWriteArrayList();
        List<AppUserVo> appUserManageList1;
        childrenList.addAll(firstChildrenList);
        for (AppUserVo appUserVo1 : firstChildrenList){
            appUserManageList1 = appUserService.getChildrenNodeByParentVipCode(appUserVo1.getVip_code());
            childrenList.addAll(appUserManageList1);
            getChildrenNodeByParentVipCode(null,appUserManageList1) ;
        }
        logger.info("静态收益 参与均分人头数 : "+ childrenList.size());
        double avgScore =   weightScore/childrenList.size();
        // -- 这里扣除 10%
        logger.info("静态收益 参与均分结果  : "+ avgScore);
        avgScore = charging(avgScore);
        updateDealData(avgScore,childrenList,rechargeUserVo.getVip_code());

        return false;
    }


    /**
     *  加权计算 团队下的全部人，先求总数 然后再求和
     *  树形结构 父节点查询子节点 最好存在在redis中 ，取数据方便快捷
     * teamCount
     * */
    public void getChildrenNodeByParentVipCode(String vipCode ,List<AppUserVo> appUserManageList1 ){
        for (AppUserVo appUserVo1 : appUserManageList1){
            appUserManageList1 = appUserService.getChildrenNodeByParentVipCode(appUserVo1.getVip_code());
            childrenList.addAll(appUserManageList1);
            getChildrenNodeByParentVipCode(appUserVo1.getVip_code(),appUserManageList1);
        }
    }

    /**
     *  分享奖
     *  //- - 计算方式
         级别       3000元        9000元        30000元       60000元0
         ↓	         ↓              ↓            ↓           ↓
         分享奖      8%            10%             12%          15%
        1.通过额度获取百分比
        2.通过比较得出最低的额度乘百分比
        3.修改个人团队数 和 奖金数 通过判断
     * */
    public boolean  insertShareAward( ) throws ApiSQLException{
        String vipCode  = rechargeUserVo.getVip_code();
         double awards = rechargeUserVo.getAwards();

        logger.info("----------------  分享奖start ------------------------");
        // 上级直接对接人
          parentUserVo = getAppUser(getAppUser(vipCode).getPush_code());
        if(parentUserVo == null ){
            // 没有上级对接人
            return false;
        }
        // 根据额度 得到百分比
        double percentage =   getPercentage("share_award_level",
               String.valueOf( VipUtils.shareMap.get(Double.valueOf(awards).intValue()) ) ,
                        true);
        logger.info("分享奖额度 得到百分比："+percentage);
        //-- 得出增长额度
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.where(" vip_code = {0}  "  , parentUserVo.getVip_code(),2);
        entityWrapper.orderBy("create_time",false);
         List<AppRecharge> list =    appRechargeService.selectList(entityWrapper);
         if(list == null || list.isEmpty()){
             return  false;
         }
        AppRecharge appRecharge = list.get(0);
        double quota  = appRecharge.getMoneys() >=  awards ? awards : parentUserVo.getAwards();
        bd = new BigDecimal(quota * percentage);
        bd.setScale(2);
        //-- 扣除运行费用
        logger.info("费用："+ bd.doubleValue());
        double shareScore = charging( bd.doubleValue() ) ;
        boolean isWrite = parentUserVo.getPresent_score() >=  shareScore  ?  true :  false;

        AppScoreLog appScoreLog = new AppScoreLog();
        if(isWrite){
            appScoreLog.setVip_code(parentUserVo.getVip_code());
            appScoreLog.setNew_score(VipUtils.score_1);
            appScoreLog.setOld_score(VipUtils.score_1);
            appScoreLog.setNum_value(shareScore );
            appScoreLog.setType(2);
            appScoreLog.setCreate_time(new Date());
            boolean b = appScoreLogService.insert(appScoreLog);
            if(!b){
                logger.info(parentUserVo.getVip_code()+" :");
                logger.info(" 分享奖送现金积分失败");
                throw new ApiSQLException(4004,"分享奖送现金积分失败");
            }
            parentUserVo.setCash_score(shareScore);
            appUserManageService.updateAppUserManageByObject(parentUserVo);
        }else{// --- 插入一条日志 告知不能满足当前条件
            appScoreLog.setVip_code(parentUserVo.getVip_code());
            appScoreLog.setNew_score(VipUtils.score_1);
            appScoreLog.setOld_score(VipUtils.score_1);
            appScoreLog.setNum_value(shareScore );
            appScoreLog.setType(3);
            appScoreLog.setCreate_time(new Date());
            appScoreLogService.insert(appScoreLog);
        }
        logger.info("----------------  分享奖end ------------------------");
        return false;
    }


    /**
     * 获取AppUser 的办法
     * */
    public AppUserVo getAppUser(String appUserCode){
        if(appUserCode == null){
            return null;
        }
        AppUserVo appUserVo =  redisCacheUtil.getCacheObject(RedisBeanUtils.USER_VO_MAP+"_"+appUserCode);
        if (appUserVo == null ){
            AppUser appUser1 = new AppUser();
            appUser1.setVip_code(appUserCode);
            List<AppUserVo> userVoList = appUserService.selectUserVoListByParam(appUserVo);
            if( userVoList == null || userVoList.isEmpty() ){
                return null;
            }
            appUserVo = userVoList.get(0);
            redisCacheUtil.setCacheObject(RedisBeanUtils.USER_VO_MAP+"_"+appUserVo.getVip_code(),appUserVo);
        }
        return appUserVo ;
    }

    /**
     * 内部类
     * 对list 进行升徐排列
     * */
    class CompareUnit implements Comparator<AppUserVo> {
        @Override
        public int compare(AppUserVo t1, AppUserVo t2) {
            if(t1.getVip_level()<t2.getVip_level()){
                return -1;
            }
            if(t1.getVip_level()>t2.getVip_level()){
                return 1;
            }
            return 0;
        }
    }

    /**
     * 获取基础配置信息
     * table app_base data
     * */
    public AppBase getAppBase(String type,String key){
        logger.info("--------------------------------------------");
        logger.info(RedisBeanUtils.APP_BASE_MAP+"_"+type+"_"+key);
        logger.info("--------------------------------------------");
        AppBase base = baseRedisCacheUtil.getCacheObject(RedisBeanUtils.APP_BASE_MAP+"_"+type+"_"+key);
        if(base == null ){
            base = new AppBase();
            base.setType(type);
            base.setKey(key);
            List<AppBase> appBaseList =  appBaseService.selectListByObject(base);
            if(appBaseList == null || appBaseList.isEmpty() ){
                return null;
            }
            base = appBaseList.get(0);
        }
        return base;
    }


    /**
     *  扣费模块
     *  基础数据模块
     * */
    public double charging(double beforeCharging){

        logger.info(" -------------- 扣除 网络维护费、总收益费、爱心基金费 begin --------------------------:"+beforeCharging);
        //网络维护费
        double taxation1  = getPercentage("taxation_type","2",false) ;
        //总收益费
        double taxation2  = getPercentage("taxation_type","3",false);
        //爱心基金费
        double taxation3  =  getPercentage("taxation_type","4",false);
        bd = new BigDecimal(taxation1+taxation2+taxation3);
        bd.setScale(2);
        double afterCharging = beforeCharging * (1-bd.doubleValue()/100);
        logger.info(" -------------- 扣除 网络维护费、总收益费、爱心基金费 end --------------------------:"+afterCharging);
        return afterCharging;
    }

    /**
     * 费率计算表
     * */
    public double  getPercentage(String key,String value,boolean isPercentage){
        bd = new BigDecimal(getAppBase(key,value).getPercentage());
        bd.setScale(2);
        if(isPercentage){
            return  bd.doubleValue()/100;
        }
        return  bd.doubleValue();
    }


    /**
     * 流水记录，
     * 1.运行维护费 日志
     * 2.积分变动记录
     * */
    public void insertScoreLog(int table,List list){
        if(table == log_score_table){
            appScoreLogMapper.insertBatch(list);
        }
    }

}
